﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.IO;

namespace Framework.WebmasterTool.Memberships
{
    public partial class CreateUser : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            string UserName = Request.QueryString["UserName"] == null ? "" : Request.QueryString["UserName"].ToString();
            MembershipUser someUser = Membership.GetUser(UserName);
            MembershipUser currentUser = Membership.GetUser();
            if (someUser != null && someUser.UserName == "admin" && currentUser.UserName != "admin")
            {
                Response.Redirect("ManageUsers.aspx");
            }
            if (!IsPostBack)
            {
                CheckPermission();
                //CleanImageUploadTemp();
                CallImageUploads();
                if (someUser == null)
                {
                    BindRoles(someUser, currentUser);
                }
                else
                {
                    BindRoles(someUser, currentUser);
                    LoadProfile(someUser, currentUser);
                }
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.ManagerUser.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CallImageUploads()
        {
            ImageUpload(siuUploadAvatar);
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void BindRoles(MembershipUser someUser, MembershipUser currentUser)
        {
            string strAdministrator = "Super Administrator";
            if (currentUser != null && Roles.IsUserInRole(currentUser.UserName, strAdministrator) == true)
            {
                string[] roles = Roles.GetAllRoles();
                chklistRoles.DataSource = roles;
                chklistRoles.DataBind();
            }
            else
            {
                string[] roles = Roles.GetAllRoles();
                chklistRoles.DataSource = roles.Where(rl => !rl.Contains(strAdministrator));
                chklistRoles.DataBind();
            }
            if (someUser != null)
            {
                foreach (string role in Roles.GetRolesForUser(someUser.UserName))
                    chklistRoles.Items.FindByText(role).Selected = true;
            }
        }

        public void LoadProfile(MembershipUser someUser, MembershipUser currentUser)
        {
            udv_Users user = entity.udv_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            txtUserName.Text = user.UserName;
            txtUserName.Enabled = false;
            txtPassword.Enabled = false;
            txtRePassword.Enabled = false;
            rfvPass.Enabled = false;
            rfvRePass.Enabled = false;
            cevEqualPass.Enabled = false;
            txtEmail.Text = user.Email;
            txtPhone.Text = user.Phone;
            txtFirstName.Text = user.FirstName;
            txtLastName.Text = user.LastName;
            if (user.ImageUrl.Trim() != "")
            {
                string sourceImageFilePath = ConfigPaths.Path_ImageAvatar_Folder_MapPath + user.ImageUrl.Trim();
                siuUploadAvatar.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
            }
            if (currentUser.UserName != "admin" && currentUser.UserName != someUser.UserName && Roles.GetRolesForUser(someUser.UserName).Contains("Administrator"))
            {
                txtEmail.Enabled = false;
                txtFirstName.Enabled = false;
                txtLastName.Enabled = false;
                txtPhone.Enabled = false;
                chklistRoles.Enabled = false;
                btnSave.Enabled = false;
            }
        }

        private void AddUser(List<string> tempRoles, MembershipUser memberShipUser)
        {
            Roles.AddUserToRoles(memberShipUser.UserName, tempRoles.ToArray());
            udv_Users newUser = new udv_Users();
            newUser.aspnet_Users = entity.aspnet_Users.Where(au => au.UserName == memberShipUser.UserName).FirstOrDefault();
            newUser.UserName = memberShipUser.UserName;
            newUser.Email = txtEmail.Text.Trim();
            newUser.FirstName = txtFirstName.Text.Trim();
            newUser.LastName = txtLastName.Text.Trim();
            newUser.Phone = txtPhone.Text.Trim();
            newUser.AddedDate = DateTime.Now;
            newUser.AddedBy = Membership.GetUser().UserName;
            newUser.IsActive = true;
            newUser.Visible = true;
            if (siuUploadAvatar.HasNewImage == true)
            {
                string fileNameAvatar = Globals.GetFileName(siuUploadAvatar.SourceImageClientFileName);
                siuUploadAvatar.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageAvatar_Folder + fileNameAvatar);
                newUser.ImageUrl = fileNameAvatar;
            }
            else
            {
                newUser.ImageUrl = "";
            }
            entity.AddToudv_Users(newUser);
            entity.SaveChanges();
        }

        private void UpdateUser(List<string> tempRoles, string UserName, MembershipUser someUser)
        {
            //dau tien xoa tat ca roles cua user
            string[] currRoles = Roles.GetRolesForUser(UserName);
            if (currRoles.Length > 0)
                Roles.RemoveUserFromRoles(UserName, currRoles);
            //sau do add lai cac roles moi cho user
            Roles.AddUserToRoles(UserName, tempRoles.ToArray());
            //sua email
            someUser.Email = txtEmail.Text.Trim();
            Membership.UpdateUser(someUser);
            //update thong tin udv_user
            udv_Users user = entity.udv_Users.Where(us => us.UserName == UserName).FirstOrDefault();
            user.Email = txtEmail.Text.Trim();
            user.FirstName = txtFirstName.Text.Trim();
            user.LastName = txtLastName.Text.Trim();
            user.Phone = txtPhone.Text.Trim();
            if (siuUploadAvatar.HasNewImage == true)
            {
                Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageAvatar_Folder_MapPath + user.ImageUrl.Trim()));
                string fileNameAvatar = Globals.GetFileName(siuUploadAvatar.SourceImageClientFileName);
                siuUploadAvatar.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageAvatar_Folder + fileNameAvatar);
                user.ImageUrl = fileNameAvatar;
            }
            if (siuUploadAvatar.HasImage == false)
            {
                Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageAvatar_Folder_MapPath + user.ImageUrl.Trim()));
                user.ImageUrl = "";
            }
            entity.SaveChanges();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<string> tempRoles = new List<string>();
            foreach (ListItem item in chklistRoles.Items)
            {
                if (item.Selected)
                    tempRoles.Add(item.Text);
            }
            if (tempRoles.Count > 0)
            {
                string UserName = Request.QueryString["UserName"] == null ? "" : Request.QueryString["UserName"].ToString();
                MembershipUser someUser = Membership.GetUser(UserName);
                if (someUser != null)
                {
                    try
                    {
                        UpdateUser(tempRoles, UserName, someUser);

                        //create db log
                        CreateDBLog(null, null, TypeAction.Update, "Cập nhật thông tin thành viên: " + UserName, "", "", "", "",
                            "", "", "", "");

                        //CleanImageUploadTemp();
                        //data cache
                        Cache.Remove("User");
                        Response.Redirect("ManageUsers.aspx");
                    }
                    catch
                    {
                        lblMsg.Text = "Email này đã tồn tại trong hệ thống";
                        return;
                    }
                }
                else
                {
                    MembershipCreateStatus status;
                    MembershipUser memberShipUser = Membership.CreateUser(txtUserName.Text.Trim(), txtPassword.Text, txtEmail.Text.Trim(), "yes", "yes", true, out status);
                    if (memberShipUser != null)
                    {
                        AddUser(tempRoles, memberShipUser);

                        //create db log
                        CreateDBLog(null, null, TypeAction.Insert, "Thêm thành viên: " + txtUserName.Text.Trim(), "", "", "", "",
                            "", "", "", "");

                        //CleanImageUploadTemp();
                        //data cache
                        Cache.Remove("User");
                        Response.Redirect("ManageUsers.aspx");
                    }
                    else
                    {
                        switch (status)
                        {
                            case MembershipCreateStatus.DuplicateEmail:
                                lblMsg.Text = "Email này đã tồn tại trong hệ thống";
                                break;
                            case MembershipCreateStatus.DuplicateUserName:
                                lblMsg.Text = "Tên đăng nhập này đã tồn tại trong hệ thống";
                                break;
                            case MembershipCreateStatus.InvalidPassword:
                                lblMsg.Text = "Mật khẩu phải ít nhất 5 ký tự";
                                break;
                            default:
                                lblMsg.Text = status.ToString() + ".";
                                break;
                        }
                    }
                }
            }
            else
            {
                lblMsg.Text = "Chưa chọn quyền cho người dùng";
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManageUsers.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}